<template>
  <a-row :gutter="10">
    <a-col :span="24">
      <a-card :bordered="false">
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
          <a-form layout="inline" @keyup.enter.native="searchQuery">
            <a-row :gutter="24">
            </a-row>
          </a-form>
        </div>
        <!-- 查询区域-END -->

        <!-- 操作按钮区域 -->
        <div class="table-operator">
          <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
          <a-button type="primary" icon="download" @click="handleExportXls('供应商信息')">导出</a-button>
          <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">
            <a-button type="primary" icon="import">导入</a-button>
          </a-upload>
          <!-- 高级查询区域 -->
          <j-super-query :fieldList="superFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQueryWithSupplierType"></j-super-query>
          <a-dropdown v-if="selectedRowKeys.length > 0">
            <a-menu slot="overlay">
              <a-menu-item key="1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>
            </a-menu>
            <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
          </a-dropdown>
        </div>

        <!-- table区域-begin -->
        <div>
          <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
            <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
            <a style="margin-left: 24px" @click="onClearSelected">清空</a>
          </div>

          <a-table
            ref="table"
            size="middle"
            bordered
            rowKey="id"
            class="j-table-force-nowrap1"
            :scroll="{x:true}"
            :columns="columns"
            :dataSource="dataSource"
            :pagination="ipagination"
            :loading="loading"
            :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
            :customRow="clickThenSelect"
            @change="handleTableChange">

            <template slot="htmlSlot" slot-scope="text">
              <div v-html="text"></div>
            </template>
            <template slot="imgSlot" slot-scope="text,record">
              <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
              <img v-else :src="getImgView(text)" :preview="record.id" height="25px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;"/>
            </template>
            <template slot="fileSlot" slot-scope="text">
              <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
              <a-button
                v-else
                :ghost="true"
                type="primary"
                icon="download"
                size="small"
                @click="downloadFile(text)">
                下载
              </a-button>
            </template>

            <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>

          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a @click="handleDetail(record)">详情</a>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>

          </a-table>
        </div>

        <supplier-information-modal ref="modalForm" @ok="modalFormOk"/>
      </a-card>
    </a-col>
    <a-col :span="24">
      <a-card :bordered="false">
      <a-tabs defaultActiveKey="1">
        <a-tab-pane tab="物料信息" key="1">
          <a-table
            ref="table"
            size="middle"
            bordered
            rowKey="id"
            class="j-table-force-nowrap1"
            :scroll="{x:true}"
            :columns="detail.columns"
            :dataSource="detail.dataSource"
            :pagination="detail.ipagination"
            :loading="loading"
            @change="handleDetailTableChange">
          </a-table>
        </a-tab-pane>
      </a-tabs>
      </a-card>
    </a-col>
  </a-row>
</template>

<script>

  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import SupplierInformationModal from './modules/SupplierInformationModal'
  import '@/assets/less/TableExpand.less'
  import { JVXETypes } from '@comp/jeecg/JVxeTable'
  import { downFile, getAction } from '@api/manage'

  export default {
    name: "SupplierInformationList",
    mixins:[JeecgListMixin],
    components: {
      SupplierInformationModal
    },
    data () {
      return {
        // 添加默认查询参数
        queryParam: {
          supplierType: 1
        },
        ipagination:{
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['5', '10', '20', '50'],
          showTotal: (total, range) => {
            return range[0] + "-" + range[1] + " 共" + total + "条"
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        description: '供应商信息管理页面',
        // 表头
        columns: [
          {
            title: '序号',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'供应商编码',
            align:"center",
            dataIndex: 'supplierCode'
          },
          {
            title:'供应商名称',
            align:"center",
            dataIndex: 'supplierName'
          },
          {
            title:'联系人',
            align:"center",
            dataIndex: 'contact'
          },
          {
            title:'联系电话',
            align:"center",
            dataIndex: 'phone'
          },
          {
            title:'备注',
            align:"center",
            dataIndex: 'note'
          },
          {
            title:'创建人',
            align:"center",
            dataIndex: 'createBy_dictText'
          },
          {
            title:'创建时间',
            align:"center",
            dataIndex: 'createTime'
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            fixed:"right",
            width:147,
            scopedSlots: { customRender: 'action' },
          }
        ],
        detail:{
          ipagination:{
            current: 1,
            pageSize: 10,
            pageSizeOptions: ['5', '10', '20', '50'],
            showTotal: (total, range) => {
              return range[0] + "-" + range[1] + " 共" + total + "条"
            },
            showQuickJumper: true,
            showSizeChanger: true,
            total: 0
          },
          columns:[
            {
              title: '序号',
              dataIndex: '',
              key:'rowIndex',
              width:60,
              align:"center",
              customRender:function (t,r,index) {
                return parseInt(index)+1;
              }
            },
            {
            title: '物料编码',
            dataIndex: 'materialCode',
            align:"center",
            },
            {
              title: '物料名称',
              dataIndex: 'materialName',
              align: "center",
            },
            {
              title: '规格型号',
              dataIndex: 'specification',
              type: JVXETypes.input,
              align: "center",
            },
            {
              title: '主单位',
              dataIndex: 'mainUnit_dictText',
              align: "center",
            },
            {
              title: '辅单位',
              dataIndex: 'deputyUnit_dictText',
              align: "center",
            },
            {
              title: '换算率',
              dataIndex: 'conversionRate',
              align: "center",
            },
          ],
          dataSource:[]
        },
        url: {
          list: "/procurement/supplierInformation/list",
          delete: "/procurement/supplierInformation/delete",
          deleteBatch: "/procurement/supplierInformation/deleteBatch",
          exportXlsUrl: "/procurement/supplierInformation/exportXls",
          importExcelUrl: "procurement/supplierInformation/importExcel",

        },
        dictOptions:{},
        superFieldList:[],
      }
    },
    created() {
      this.getSuperFieldList();
      // 确保 queryParam 初始化并包含 supplierType
      if (!this.queryParam) {
        this.queryParam = {};
      }
      this.queryParam.supplierType = 1;
    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      }
    },
    methods: {
// 重写 loadData 方法
      loadData(arg) {
        if (arg === 1) {
          this.ipagination.current = 1;
        }

        const params = this.getQueryParams();
        // 确保 supplierType 参数存在
        params.supplierType = 1;

        console.log('查询参数:', params);

        this.loading = true;
        getAction(this.url.list, params).then((res) => {
          if (res.success) {
            this.dataSource = res.result.records || res.result;
            this.ipagination.total = res.result.total || 0;
          } else {
            this.$message.warning(res.message);
          }
          this.loading = false;
        });
      },

      // 重写获取查询参数方法
      getQueryParams() {
        // 获取基本查询参数
        const param = {
          pageNo: this.ipagination.current,
          pageSize: this.ipagination.pageSize,
          ...this.queryParam
        };

        // 添加排序参数
        if (this.isorter && this.isorter.column) {
          param.column = this.isorter.column;
          param.order = this.isorter.order;
        }

        // 添加高级查询参数
        if (this.superQueryParams) {
          param.superQueryParams = this.superQueryParams;
          param.superQueryMatchType = this.superQueryMatchType;
        }

        // 确保 supplierType 参数存在
        param.supplierType = 1;

        return param;
      },

      // 优化后的高级查询处理方法
      handleSuperQueryWithSupplierType(arg) {
        console.log('原始高级查询参数:', arg);

        // 如果没有参数，直接使用默认查询条件
        if (!arg || arg.length === 0) {
          // 清空高级查询参数
          this.superQueryParams = null;
          this.loadData(1);
          return;
        }

        // 详细检查每个条件
        if (arg && arg.length > 0) {
          console.log('原始条件详情:');
          arg.forEach((item, index) => {
            console.log(`条件 ${index}:`, JSON.stringify(item));
          });
        }

        // 创建一个新数组，避免修改原始参数
        let storeField = [];

        // 添加用户选择的所有条件，放宽验证
        for (let item of arg) {
          // 只要有 value 属性就认为是有效条件
          if (item && item.val) {
            // 深拷贝条件对象，避免引用问题
            const conditionItem = JSON.parse(JSON.stringify(item));
            console.log('添加条件:', JSON.stringify(conditionItem));
            storeField.push(conditionItem);
          } else {
            console.log('忽略无效条件:', JSON.stringify(item));
          }
        }

        console.log('处理后的条件数组:', storeField);

        // 检查是否已经包含 supplierType 条件
        const hasSupplierType = storeField.some(item => item.value === 'supplierType');

        // 如果没有 supplierType 条件，添加它
        if (!hasSupplierType) {
          const supplierTypeCondition = {
            type: 'int',
            value: 'supplierType',
            text: '供应商类型',
            dictCode: '',
            val: '1',
            rule: 'eq'
          };
          console.log('添加 supplierType 条件:', supplierTypeCondition);
          storeField.push(supplierTypeCondition);
        }

        console.log('最终高级查询条件:', storeField);

        // 将条件转换为 JSON 字符串
        if (storeField.length > 0) {
          this.superQueryParams = JSON.stringify(storeField);
          console.log('设置的 superQueryParams:', this.superQueryParams);
        } else {
          this.superQueryParams = null;
          console.log('未设置 superQueryParams，因为没有有效条件');
        }

        // 加载数据
        this.loadData(1);
      },
      // 原始的高级查询处理方法
      handleSuperQuery(arg) {
        console.log('处理高级查询条件:', arg);

        if(!arg || !arg.length) {
          this.superQueryParams = null;
          this.loadData(1);
          return;
        }

        let storeField = [];
        for (let item of arg) {
          if (item.value) {
            storeField.push({ ...item });
          }
        }

        // 检查是否已经包含 supplierType 条件
        const hasSupplierType = storeField.some(item => item.value === 'supplierType');

        // 如果没有 supplierType 条件，添加它
        if (!hasSupplierType) {
          storeField.push({
            type: 'int',
            value: 'supplierType',
            text: '供应商类型',
            dictCode: '',
            val: '1',
            rule: 'eq'
          });
        }

        console.log('最终高级查询条件:', storeField);

        this.superQueryParams = JSON.stringify(storeField);
        console.log('设置的 superQueryParams:', this.superQueryParams);

        this.loadData(1);
      },

      // 重写导出方法，确保导出时包含 supplierType 条件
      handleExportXls(fileName) {
        if (!fileName || typeof fileName != "string") {
          fileName = "导出文件"
        }
        let param = { ...this.queryParam };
        if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
          param['selections'] = this.selectedRowKeys.join(",")
        }
        // 确保导出时包含 supplierType 条件
        param.supplierType = 1;

        console.log("导出参数", param);
        this.loading = true;
        downFile(this.url.exportXlsUrl, param).then((data) => {
          if (!data) {
            this.$message.warning("文件下载失败")
            return
          }
          if (typeof window.navigator.msSaveBlob !== 'undefined') {
            window.navigator.msSaveBlob(new Blob([data], {type: 'application/vnd.ms-excel'}), fileName + '.xls')
          } else {
            let url = window.URL.createObjectURL(new Blob([data], {type: 'application/vnd.ms-excel'}))
            let link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', fileName + '.xls')
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link); //下载完成移除元素
            window.URL.revokeObjectURL(url); //释放掉blob对象
          }
        })
      },
      handleDetailTableChange(pagination, filters, sorter) {
        //分页、排序、筛选变化时触发
        //TODO 筛选
        console.log(pagination)
        if (Object.keys(sorter).length > 0) {
          this.isorter.column = sorter.field;
          this.isorter.order = "ascend" == sorter.order ? "asc" : "desc"
        }
        this.detail.ipagination = pagination;
        this.onSelectChange(this.selectedRowKeys,this.selectionRows)
      },
      clickThenSelect(record){
        return {
          onClick:()=>{
            this.onSelectChange(record.id.split(","), [record]);
          }
        }
      },
      onSelectChange(selectedRowKeys, selectionRows) {
        this.selectedRowKeys = selectedRowKeys;
        this.selectionRows = selectionRows;
        console.log(this.selectedRowKeys,this.selectionRows)
        this.detail.dataSource=[]
        let ids = selectedRowKeys.join(",")
        console.log("222131",ids)

        getAction('/procurement/supplierInformation/getGoodsBySupplier',
          {supplierId:ids,
                     pageNo:this.detail.ipagination.current,
                     pageSize:this.detail.ipagination.pageSize}).then(res=>{
          if (res.success){
            this.detail.dataSource=res.result.records
            this.detail.ipagination.total=res.result.total

          }
        })
      },
      initDictConfig(){
      },
      getSuperFieldList(){
        let fieldList=[];
        fieldList.push({type:'string',value:'supplierCode',text:'供应商编码',dictCode:''})
        fieldList.push({type:'string',value:'supplierName',text:'供应商名称',dictCode:''})
        fieldList.push({type:'string',value:'contact',text:'联系人',dictCode:''})
        fieldList.push({type:'string',value:'phone',text:'联系电话',dictCode:''})
        fieldList.push({type:'string',value:'note',text:'备注',dictCode:''})
        fieldList.push({type:'string',value:'legalRepresentativeName',text:'法定代表人',dictCode:''})
        fieldList.push({type:'string',value:'address',text:'地址',dictCode:''})
        fieldList.push({type:'string',value:'appointedAgentName',text:'委托代理人',dictCode:''})
        fieldList.push({type:'string',value:'taxCode',text:'税号',dictCode:''})
        fieldList.push({type:'string',value:'bank',text:'开户行',dictCode:''})
        fieldList.push({type:'string',value:'zipCode',text:'邮政编码',dictCode:''})
        this.superFieldList = fieldList
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>